﻿using System;
using System.Net;
using System.Net.Mail;
using System.IO;
using System.Text;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Web;
using System.Web.Security;
using System.Security.Cryptography;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Collections.Generic;

using Jungle.Code.DAL;
using Jungle.Code.Utils;

namespace Jungle.Users
{
    public class UserManager
    {
        private string ConnectionString = DBHelper.ConnectionString;
        public DataSet ds = new DataSet();

        public string err;

        public UserManager()
        { 
        
        }

        public UserManager(int _UserId)
        {
            userId = _UserId;
            GetById();
        }

        #region Fileds
            private int userId;
            private string email;
            private string password;    
            private string name;
            private string fname;
            private int country;
            private string city;
            private string photo;
            private string phone;
            private DateTime regDate;
            private string activation;
            private int roleId;
            private string mobile;
        #endregion

        public List<UserManager> UserList;

        #region Properties
            public int UserId { get { return userId; } set { userId = value; } }
            public string Email { get { return email; } set { email = value; } }
            public string Password { get { return password; } set { password = value; } }
            public string Name { get { return name; } set { name = value; } }
            public string Fname { get { return fname; } set { fname = value; } }
            public int Country { get { return country; } set { country = value; } }
            public string City { get { return city; } set { city = value; } }
            public string Photo { get { return photo; } set { photo = value; } }
            public string Phone { get { return phone; } set { phone = value; } }
            public DateTime RegDate { get { return regDate; } set { regDate = value; } }
            public string Activation { get { return activation; } set { activation = value; } }
            public int RoleId { get { return roleId; } set { roleId = value; } }
            public string Mobile { get { return mobile; } set { mobile = value; } }
        #endregion
        //------------------------------------------------------------------------------------
        public void Add()
        {
            SqlConnection connect = new SqlConnection(ConnectionString);
            SqlCommand command = new SqlCommand("users.mdUsers_AddUser", connect);
            SqlDataReader reader = null;
            command.CommandType = CommandType.StoredProcedure;
            try
            {
                command.Parameters.Add("@Email", SqlDbType.VarChar, 128).Value = email;
                command.Parameters.Add("@Password", SqlDbType.VarChar, 32).Value = password;
                command.Parameters.Add("@Name", SqlDbType.VarChar, 32).Value = name;
                command.Parameters.Add("@Fname", SqlDbType.VarChar, 32).Value = fname;
                command.Parameters.Add("@CountryId", SqlDbType.Int).Value = country;
                command.Parameters.Add("@City", SqlDbType.VarChar,64).Value = city;
                command.Parameters.Add("@Mobile", SqlDbType.VarChar, 32).Value = mobile;
                command.Parameters.Add("@Phone", SqlDbType.VarChar, 32).Value = phone;
                command.Parameters.Add("@Activation", SqlDbType.VarChar, 32).Value = activation;
                command.Parameters.Add("@RoleId", SqlDbType.Int).Value = roleId;


               
                command.Connection.Open();
                reader = command.ExecuteReader();
                while (reader.Read())
                {
                    userId = Convert.ToInt32(reader.GetValue(0));
                }
                reader.Close();
              
            }
            catch (SqlException ex)
            {
                err = ex.ToString();
                
            }
            finally
            {
                command.Connection.Close();
            }
        }
        //------------------------------------------------------------------------------------
        public void Update()
        {
            using (SqlConnection connect = new SqlConnection(ConnectionString))
            {
                SqlCommand command = new SqlCommand("users.mdUsers_Update", connect);
                command.CommandType = CommandType.StoredProcedure;

                command.Parameters.Add("@UserId", SqlDbType.Int).Value = userId;
                command.Parameters.Add("@Email", SqlDbType.VarChar, 128).Value = email;
                command.Parameters.Add("@Password", SqlDbType.VarChar, 32).Value = password;
                command.Parameters.Add("@Name", SqlDbType.VarChar, 32).Value = name;
                command.Parameters.Add("@Fname", SqlDbType.VarChar, 32).Value = fname;
                command.Parameters.Add("@CountryId", SqlDbType.Int).Value = country;
                command.Parameters.Add("@City", SqlDbType.VarChar, 64).Value = city;
                command.Parameters.Add("@Mobile", SqlDbType.VarChar, 32).Value = mobile;
                command.Parameters.Add("@Phone", SqlDbType.VarChar, 32).Value = phone;
                command.Parameters.Add("@Activation", SqlDbType.VarChar, 32).Value = activation;
                command.Parameters.Add("@RoleId", SqlDbType.Int).Value = roleId;

                command.Connection.Open();
                command.ExecuteNonQuery();
                command.Connection.Close();
            }
        }
        //------------------------------------------------------------------------------------
        public bool Login()
        {
            bool bl=false;
            SqlConnection connect = new SqlConnection(ConnectionString);
            SqlDataReader reader = null;
            SqlCommand command = new SqlCommand("users.mdUsers_GetByLoginPass", connect);
            command.CommandType = CommandType.StoredProcedure;
            try
            {
                command.Parameters.Add("@Email", SqlDbType.VarChar, 128).Value = email;
                command.Parameters.Add("@Password", SqlDbType.VarChar, 32).Value = password;

                command.Connection.Open();
                reader = command.ExecuteReader();
                if (reader.Read())
                {
                    userId = Convert.ToInt32(reader.GetValue(0));
                    bl= true;
                }
            }
             catch (SqlException ex)
            {
                err = ex.ToString();
                bl=false;
            }
            finally
            {
                reader.Close();
                command.Connection.Close();
            }
                return bl;
           
        }
        //------------------------------------------------------------------------------------
        public void Delete()
        {
            SqlConnection connect = new SqlConnection(ConnectionString);
            SqlCommand command = new SqlCommand(" delete from users.mdUsers where [UserId]=" + userId.ToString(), connect);
            try
            {
                command.Connection.Open();
                command.ExecuteNonQuery();
                command.Connection.Close();
            }
            catch (SqlException ex)
            {
                err = ex.ToString();
            }
            finally
            {
                connect.Close();
            }
        }
        //------------------------------------------------------------------------------------
        public void GetById()
        {
            using (SqlConnection connect = new SqlConnection(ConnectionString))
            {
                SqlCommand command = new SqlCommand("users.mdUsers_GetById", connect);
                SqlDataReader reader = null;

                command.CommandType = CommandType.StoredProcedure;
                command.Parameters.Add("@UserId", SqlDbType.Int).Value = userId;

                command.Connection.Open();
                reader = command.ExecuteReader();
                while (reader.Read())
                {
                    userId = (int)reader["UserId"];
                    email = reader["Email"].ToString().Trim();
                    password = reader["Password"].ToString();
                    name = reader["Name"].ToString().Trim();
                    fname = reader["Fname"].ToString().Trim();
                    country = (int)reader["CountryId"];
                    city = reader["City"].ToString().Trim();
                    mobile = reader["Mobile"].ToString().Trim();
                    phone = reader["Phone"].ToString().Trim();
                    regDate = (DateTime)reader["RegDate"];
                    activation = reader["Activation"].ToString().Trim();
                    roleId = (int)reader["RoleId"];
                }
                reader.Close();
                command.Connection.Close();
            }
        }
        //------------------------------------------------------------------------------------
        public void GetByEmail()
        {
            using (SqlConnection connect = new SqlConnection(ConnectionString))
            {
                SqlCommand command = new SqlCommand("select * from users.mdUsers where [Email]='" + email + "'", connect);
                SqlDataReader reader = null;

                command.Connection.Open();
                reader = command.ExecuteReader();
                while (reader.Read())
                {
                    userId = (int)reader["UserId"];
                    email = reader["Email"].ToString().Trim();
                    password = reader["Password"].ToString();
                    name = reader["Name"].ToString().Trim();
                    fname = reader["Fname"].ToString().Trim();
                    country = (int)reader["CountryId"];
                    city = reader["City"].ToString().Trim();
                    mobile = reader["Mobile"].ToString().Trim();
                    phone = reader["Phone"].ToString().Trim();
                    regDate = (DateTime)reader["RegDate"];
                    activation = reader["Activation"].ToString().Trim();
                    roleId = (int)reader["RoleId"];
                }
                reader.Close();
                command.Connection.Close();
            }
        }
        //------------------------------------------------------------------------------------
        public void GetAllUsers()
        {
            SqlConnection connect = new SqlConnection(DBHelper.ConnectionString);
            string s;
            err = null;
            try
            {
                s = "exec users.mdUsers_GetAll";
                ds.Clear();
                SqlDataAdapter myData = new SqlDataAdapter(s, connect);
                myData.Fill(ds);
            }
            catch (SqlException ex)
            {
                err = (ex.ToString());
            }
            finally
            {
                connect.Close();
            }
        }
        //------------------------------------------------------------------------------------
        public void GetAll()
        {
            using (SqlConnection connect = new SqlConnection(ConnectionString))
            {
                SqlCommand command = new SqlCommand("users.mdUsers_GetAll", connect);
                SqlDataReader reader = null;

                UserList = new List<UserManager>();
                command.CommandType = CommandType.StoredProcedure;

                command.Connection.Open();
                reader = command.ExecuteReader();
                while (reader.Read())
                {
                    UserManager um = new UserManager();
                    um.userId = (int)reader["UserId"];
                    um.GetById();

                    UserList.Add(um);
                }
                reader.Close();
                command.Connection.Close();
            }
        }
        //------------------------------------------------------------------------------------
        public static void SendEmail(string to, string subject, string body)
        {
            MailMessage message = new MailMessage("vopros@td-modeks.com", to, subject, body);
            SmtpClient client = new SmtpClient("mail.td-modeks.com", 25);
            client.Credentials = new NetworkCredential("vopros@td-modeks.com", "1234567890");

            client.Send(message);        
        }
        //------------------------------------------------------------------------------------
        public string UserLink()
        {
            string linkUserInfo = "<a style=\"color: #0071bc;\" href=\"" + UrlHelper.GetSiteUrl() + "/ru/userinfo.aspx?uId=" + userId.ToString() + "\"> " + name + ", " + fname + "</a>";
            return linkUserInfo;
        }
        //------------------------------------------------------------------------------------
        public static string UserStaticLink(int id)
        {
            UserManager um = new UserManager();
            um.userId = id;
            um.GetById();

            string linkUserInfo = "<a style=\"color: #0071bc;\" href=\"" + UrlHelper.GetSiteUrl() + "/ru/userinfo.aspx?uId=" + id.ToString() + "\"> " + um.Name + ", " + um.Fname + "</a>";
            return linkUserInfo;
        }
        //------------------------------------------------------------------------------------
        public bool CheckEmail()
        {
            bool valid = true;
            using (SqlConnection connect = new SqlConnection(ConnectionString))
            {
                SqlCommand command = new SqlCommand("users.mdUsers_GetByEmail", connect);
                command.CommandType = CommandType.StoredProcedure;
                command.Parameters.Add("@Email", SqlDbType.VarChar, 128).Value = email;
                SqlDataReader reader = null;

                command.Connection.Open();
                reader = command.ExecuteReader();
                if (reader.Read()) valid = false;
                else valid = true;
                reader.Close();
                command.Connection.Close();
            }
            return valid;
        }
        //------------------------------------------------------------------------------------
        public void GetByActivation()
        {
            using (SqlConnection connect = new SqlConnection(ConnectionString))
            {
                SqlCommand command = new SqlCommand("users.mdUsers_GetByActivation", connect);
                command.CommandType = CommandType.StoredProcedure;
                command.Parameters.Add("@Activation", SqlDbType.VarChar, 32).Value = activation;
                SqlDataReader reader = null;

                command.Connection.Open();
                reader = command.ExecuteReader();
                if (reader.Read())
                {
                    userId = (int)reader["UserId"];
                    email = reader["Email"].ToString().Trim();
                    password = reader["Password"].ToString();
                    name = reader["Name"].ToString().Trim();
                    fname = reader["Fname"].ToString().Trim();
                    country = (int)reader["CountryId"];
                    city = reader["City"].ToString().Trim();
                    mobile = reader["Mobile"].ToString().Trim();
                    phone = reader["Phone"].ToString().Trim();
                    regDate = (DateTime)reader["RegDate"];
                    activation = reader["Activation"].ToString().Trim();
                    roleId = (int)reader["RoleId"];
                }
                reader.Close();
                command.Connection.Close();
            }            
        }
        //------------------------------------------------------------------------------------
        public static string getMd5Hash(string input)
        {
            MD5 md5Hasher = MD5.Create();
            byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));
            StringBuilder sBuilder = new StringBuilder();
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }

            return sBuilder.ToString();
        }
        //-------------------------------------------------------------------------------------
        public static DataSet GetCountrys()
        {
            SqlConnection connect = new SqlConnection(DBHelper.ConnectionString);
            string s;
            DataSet ds1 = new DataSet();
            try
            {
                s = "select * from users.Countrys";

                ds1.Clear();
                SqlDataAdapter myData = new SqlDataAdapter(s, connect);
                myData.Fill(ds1);
            }
            catch
            {
            }
            finally
            {
                connect.Close();
            }
            return ds1;
        }
        //-------------------------------------------------------------------------------------
        public static DropDownList ddl_Roles()
        {
            DropDownList ddl = new DropDownList();
            using (SqlConnection connect = new SqlConnection(DBHelper.ConnectionString))
            {
                SqlCommand command = new SqlCommand("select * from users.Roles", connect);
                SqlDataReader reader = null;

                command.Connection.Open();
                reader = command.ExecuteReader();
                while (reader.Read())
                {
                    ddl.Items.Add(new ListItem(reader["Role"].ToString().Trim(), reader["RoleId"].ToString()));
                }
                reader.Close();
                command.Connection.Close();
            }
            return ddl;

        }
        //-------------------------------------------------------------------------------------
        public static string GetUserRole(int RoleId)
        {
            if (RoleId == 0) { return "Неопределена"; }
            using (SqlConnection connect = new SqlConnection(DBHelper.ConnectionString))
            {
                SqlCommand command = new SqlCommand("select * from users.Roles", connect);
                SqlDataReader reader = null;

                command.Connection.Open();
                reader = command.ExecuteReader();
                while (reader.Read())
                {
                    if(Convert.ToInt32(reader["RoleId"]) == RoleId)
                       return reader["Role"].ToString().Trim();
                }
                reader.Close();
                command.Connection.Close();
            }
            return "Не определена";
        }

    }
}